<?php
namespace Home\Controller;
use Lib\Api\OrganizationSettingApi;
use Lib\Api\RechargeWithdrawalsApi;
use Lib\Api\SysApi;
use Lib\Api\TradeDetailApi;
use Lib\Utils\PayUtils;
use Think\Controller;
class PayController extends Controller {

    public function index(){
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		$url = isLogin();
        if ($url != false) {
            header("Location:".$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        /*$modelName = 'User';
        $model = M($modelName);
        $data = $model->where(array('id' => session('user_id')))->find();
        $this->assign('user', $data);*/

        $sys = SysApi::getInfo(array('id' => 1), "lowest_recharge,highest_recharge,day_max_recharge,recharge_fee");

        $modelName = 'TradeDetail';
        $model = M($modelName);
        $where['source']  = array('eq', '2');
        $where['source']  = array('eq', '3');
        $where['source']  = array('eq', '4');
        $where['_logic'] = 'or';
        $map['_complex'] = $where;
        $map['user_id'] = array('eq', session('user_id'));
        $map['DATE_FORMAT(datetime, "%Y-%m-%d")'] = array(array('egt', date('Y-m-d')), array('elt',date('Y-m-d')));
        $recharge_money = $model->where($map)->sum("money");
        $use_recharge_money = $sys['day_max_recharge'];
        if(!empty($recharge_money) && $recharge_money > 0) {
            $use_recharge_money = $use_recharge_money - $recharge_money;
        }

        $banks = array(
            //array("name"=>"微信支付","value"=>"WXZF_h5","icon"=>"icon-ziyuanxiawu","isUse"=>1, "subUrl"=>"button", "min_money"=>12, "max_money"=>4998, "type"=>"baifupass"),
            //array("name"=>"微信支付","value"=>"WXZF_H5","icon"=>"icon-ziyuanxiawu","isUse"=>1, "subUrl"=>"button", "min_money"=>0, "max_money"=>0, "type"=>"rightyoo"),
            //array("name"=>"支付宝","value"=>"ALIPAY_h5","icon"=>"icon-zhifubaozhifu","isUse"=>1, "subUrl"=>"button", "min_money"=>0, "max_money"=>0, "type"=>"zito"),
			array("name"=>"银联快捷","value"=>"UNIONPAY","icon"=>"icon-yinlianzhifu","isUse"=>1, "subUrl"=>"button", "min_money"=>0, "max_money"=>0, "type"=>"baifupass"),
			// array("name"=>"微信扫码支付","value"=>"WXZF_web","icon"=>"icon-ziyuanxiawu","isUse"=>2, "subUrl"=>"button", "type"=>"cnzyzf"),
            array("name"=>"支付宝","value"=>"05","icon"=>"icon-zhifubaozhifu","isUse"=>1, "subUrl"=>"button", "min_money"=>0, "max_money"=>0, "type"=>"cai1pay"),

            //
        );

        $moneylist = array(103.68,203.57,506.89,1012.65,3037.53,4568.65);
        $init_date["banks"] = $banks;
        $init_date["moneylist"] = $moneylist;
        $init_date["GlobalSettingsID"] = 1;
        $init_date["EachMaximumRechargeAmount"] = $sys['highest_recharge'];
        $init_date["SingledayMaximumRechargeAmount"] = $sys['day_max_recharge'];
        $init_date["SingleMinimumAmountRecharge"] = $sys['lowest_recharge'];
        $init_date["UseRechargeMoney"] = $use_recharge_money;
        $init_date["ChargingFee"] = sprintf("%.2f", $sys['recharge_fee']);
        $this->assign('init_date', json_encode($init_date));

        $this->display();
    }

    public function checkchongzhi() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		$arr['url'] = isLogin();
        if ($arr['url'] != false) {
            $this->ajaxReturn($arr);
            exit;
        }
        if (!empty($_POST['money']) && $_POST['money'] > 0) {
            $money = $_POST['money'];

            $sys = SysApi::getInfo(array('id' => 1), "lowest_recharge,highest_recharge,day_max_recharge");

            if ($money < $sys['lowest_recharge']) {
                $ajaxdata['status'] = "no";
                $ajaxdata['msg'] = '充值金额小于最低限制';
            } else if ($money > $sys['highest_recharge']) {
                $ajaxdata['status'] = "no";
                $ajaxdata['msg'] = '充值金额超出最高限制';
            } else {
                $modelName = 'TradeDetail';
                $model = M($modelName);
                $where['source']  = array('eq', '2');
                $where['source']  = array('eq', '3');
                $where['source']  = array('eq', '4');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $map['user_id'] = array('eq', session('user_id'));
                $map['DATE_FORMAT(datetime, "%Y-%m-%d")'] = array(array('egt', date('Y-m-d')), array('elt',date('Y-m-d')));
                $recharge_money = $model->where($map)->sum("money");
                $day_max_recharge = $sys['day_max_recharge'];

                if(!empty($recharge_money) && $recharge_money > 0) {
                    $use_recharge_money = $day_max_recharge - $recharge_money;
                    if ($money>$use_recharge_money) {
                        $ajaxdata['status'] = "no";
                        $ajaxdata['msg'] = '超出当前可充值额度';
                    } else {
                        $ajaxdata['status'] = "ok";
                    }
                } else {
                    $ajaxdata['status'] = "ok";
                }
            }
        } else {
            $ajaxdata['status'] = "no";
            $ajaxdata['msg'] = '错误的充值金额';
        }
        $this->ajaxReturn($ajaxdata);

    }

    public function pay() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		$url = isLogin();
        if ($url != false) {
            header("Location:".$url);
			exit;
        }
        $money = 0;
            if (!empty($_GET["money"])) {
                $money = $_GET["money"];
            }
            if ($money <= 0) {
                exit("充值金额错误");
            }
			$sys = SysApi::getInfo(array('id' => 1), "lowest_recharge,highest_recharge");
			if ($money < $sys['lowest_recharge']) {
				exit("充值金额小于最低限制");
			} else if ($money > $sys['highest_recharge']) {
				exit("充值金额超出最高限制");
			}
            $pbank = "";
            if (!empty($_GET["pbank"])) {
                $pbank = $_GET["pbank"];
            }
            if ($pbank == "") {
                exit("请选择支付银行");
            }
            $type = "";
            if (!empty($_GET["type"])) {
                $type = $_GET["type"];
            }
            $user_id = session('user_id');
            $timestamp = date("YmdHis");

            if ($type == "") {
                exit("系统错误");
            } else if ($type == "zftong") {
                $orderNo = "zftong_".$user_id.$timestamp;    //订单号
                $result = \Lib\PayApi\Zftong\PaymentClient::pay($orderNo, $money, $pbank);
                exit($result);
            } else if ($type == "cnzyzf") {
                $orderNo = $user_id.C('CNZYZF')['__PAYNO__'].$timestamp;    //订单号
                $model = M("Pay");
                $params = array("user_id"=>$user_id, "order_id"=>$orderNo, "amount"=>"$money", "type"=>$pbank, "status"=>1, "ctime"=>date("Y-m-d H:i:s"));
                $result = $model->add($params);
                if ($result > 0) {
                    $result = \Lib\PayApi\Cnzyzf\PaymentClient::pay($orderNo, $money, $pbank);
                    $pattern = "/<[img|IMG].*?src=[\\'|\"](.*?(?:[\\.jpg|\\.jpeg|\\.png|\\.gif|\\.bmp]))[\\'|\"].*?[\\/]?>/";
                    preg_match_all($pattern,$result,$match);

                    $pattern2 = "/\\S\\s+url:'(.*?)'\\S\\s+data:\"(.*?)\"/";
                    preg_match_all($pattern2,$result,$match2);

                    $img = 'http://zy.cnzypay.com/'.$match[1][0];
                    $this->assign('img', $img);
                    $where['_string'] = "concat(b.p_code,b.level,b.code)='".session("organization_code")."'";
                    $appId = OrganizationSettingApi::getInfoByCondition($where, "left join fs_organization b on b.id = a.organization_id", "wx_appid");
                    $this->assign('appId', $appId);
                    $this->display('scan_pay');
                }
            } else if ($type == "zito") {
				$zito = C('ZITO');
                $minMoney = $zito['minMoney'];
                $maxMoney = $zito['maxMoney'];
                if ($money < $minMoney) {
                    exit("该充值通道最底充值金额为：".$minMoney."元");
                }
                if ($maxMoney > 0 && $money > $maxMoney) {
                    exit("该充值通道最高充值金额为：".$maxMoney."元");
                }
				
                $orderNo = "zito_".$user_id.$timestamp;    //订单号
                $model = M("Pay");
                $params = array("user_id"=>$user_id, "order_id"=>$orderNo, "amount"=>"$money", "type"=>$pbank, "status"=>1, "ctime"=>date("Y-m-d H:i:s"));
                $result = $model->add($params);
                if ($result > 0) {
                    $result = \Lib\PayApi\Zito\PaymentClient::pay($orderNo, $money, $pbank);
                    $result = json_decode($result, true);
                    if ($result['success'] == true && $result['code'] == "0x0000") {
                        if (strstr($pbank,"ALIPAY")) {
                            $this->assign('pay_url', urlencode($result['cashway']));
                            $this->display('scan_pay_alipay_h5');
                        } else {
                            header("Location:".$result['cashway']);
                        }
                    } else {
                        exit($result['msg']);
                    }
                }
            } else if ($type == "baifupass") {
				$baifupass = C('BAIFUPASS');
                $minMoney = $baifupass['minMoney'];
                $maxMoney = $baifupass['maxMoney'];
                if ($money < $minMoney) {
                    exit("该充值通道最底充值金额为：".$minMoney."元");
                }
                if ($maxMoney > 0 && $money > $maxMoney) {
                    exit("该充值通道最高充值金额为：".$maxMoney."元");
                }
				
                $orderNo = "baifupass".$user_id.$timestamp;    //订单号
                $model = M("Pay");
                $params = array("user_id"=>$user_id, "order_id"=>$orderNo, "amount"=>"$money", "type"=>$pbank, "status"=>1, "ctime"=>date("Y-m-d H:i:s"));
                $result = $model->add($params);
                if ($result > 0) {
                    $result = \Lib\PayApi\Baifupass\PaymentClient::pay($orderNo, $money, $pbank);
                    $result = json_decode($result, true);
                    if ($result['bftcode'] == "1000") {
                        // exit($result['result']["qrCode"]);
                        if (strstr($pbank,"UNIONPAY")) {
                            header("Location:".$result['result']["url"]);
                        } else {
                            header("Location:".$result['result']["qrCode"]);
                        }
                    } else {
                        exit($result['msg']);
                    }
                }
            } else if ($type == "yekapay") {
                $yekapay = C('YEKAPAY');
                $minMoney = $yekapay['minMoney'];
                $maxMoney = $yekapay['maxMoney'];
                if ($money < $minMoney) {
                    exit("该充值通道最底充值金额为：".$minMoney."元");
                }
                if ($maxMoney > 0 && $money > $maxMoney) {
                    exit("该充值通道最高充值金额为：".$maxMoney."元");
                }

                $orderNo = "yekapay_".$user_id.$timestamp;    //订单号
                $model = M("Pay");
                $params = array("user_id"=>$user_id, "order_id"=>$orderNo, "amount"=>"$money", "type"=>$pbank, "status"=>1, "ctime"=>date("Y-m-d H:i:s"));
                $result = $model->add($params);
                if ($result > 0) {
                    $requestarray = \Lib\PayApi\YeKaPay\PaymentClient::pay($orderNo, $money, $pbank);
                    $str = '<form id="Form1" style="display:none" name="Form1" method="post" action="' . $yekapay['baseUri'] . '">';
                    foreach ($requestarray as $key => $val) {
                        $str = $str . '<input type="hidden" name="' . $key . '" value="' . $val . '">';
                    }
                    $str = $str . '<input type="submit" value="支付">';
                    $str = $str . '</form>';
                    $str = $str . '<script>';
                    $str = $str . 'document.Form1.submit();';
                    $str = $str . '</script>';
                    exit($str);
                }
            } else if ($type == "rightyoo") {
				$rightyoo = C('RIGHTYOO');
                $minMoney = $rightyoo['minMoney'];
                $maxMoney = $rightyoo['maxMoney'];
                if ($money < $minMoney) {
                    exit("该充值通道最底充值金额为：".$minMoney."元");
                }
                if ($maxMoney > 0 && $money > $maxMoney) {
                    exit("该充值通道最高充值金额为：".$maxMoney."元");
                }
				
				$orderNo = "rightyoo_".$user_id.$timestamp;    //订单号
                $model = M("Pay");
                $params = array("user_id"=>$user_id, "order_id"=>$orderNo, "amount"=>"$money", "type"=>$pbank, "status"=>1, "ctime"=>date("Y-m-d H:i:s"));
                $result = $model->add($params);
				if ($result > 0) {
                    $result = \Lib\PayApi\Rightyoo\PaymentClient::pay($orderNo, $money, $pbank);
					$result = json_decode($result, true);
                    
                    if ($result['ret'] == "200") {
						// $this->assign('pay_url', $result['data']["pay_url"]);
						
						$domain_url = C('TMPL_PARSE_STRING.__DOMAINURL__');
						$web_site_dir = C('TMPL_PARSE_STRING.__WEBSITEDIR__');
						
						$temp_url = explode('rdurl=',$result['data']["pay_url"]);
						
		
						header("Location:".$domain_url.$web_site_dir.'/pay/pay_page?pay_url='.$temp_url[0].'rdurl='.urlencode($temp_url[1]));
						
                        // $this->display('pay_page');
                        // exit($result['result']["qrCode"]);
						
                        // header("Location:".$result['data']["pay_url"]);
                    } else {
                        exit($result['msg']);
                    }
                }
			} else if ($type == "cai1pay") {

                $cai1Pay = C('Cai1Pay');
                $minMoney = $cai1Pay['minMoney'];
                $maxMoney = $cai1Pay['maxMoney'];
                if ($money < $minMoney) {
                    exit("该充值通道最底充值金额为：" . $minMoney . "元");
                }
                if ($maxMoney > 0 && $money > $maxMoney) {
                    exit("该充值通道最高充值金额为：" . $maxMoney . "元");
                }

                $orderNo = "cai1pay_" . $user_id . $timestamp;    //订单号
                $model = M("Pay");
                $params = array("user_id" => $user_id, "order_id" => $orderNo, "amount" => "$money", "type" => $pbank, "status" => 1, "ctime" => date("Y-m-d H:i:s"));
                $result = $model->add($params);
                if ($result > 0) {
                    $requestArray = \Lib\PayApi\Cai1Pay\PaymentClient::pay($orderNo, $money, $pbank);
                    foreach($requestArray as $name=>$value) {
                        $this->assign($name, $value);
                    }
                    $this->display('redirect');

                }
            }
    }
	
	public function pay_page($pay_url) {
		$this->assign('pay_url', $pay_url);
		$this->display();
	}

    public function q_scan($codeUrl) {
        qrcode(urldecode($codeUrl), 6);
    }

    public function pay_call() {
        $ReturnArray = array( // 返回字段
            "memberid" => $_REQUEST["memberid"], // 商户ID
            "orderid" =>  $_REQUEST["orderid"], // 订单号
            "amount" =>  $_REQUEST["amount"], // 交易金额
            "datetime" =>  $_REQUEST["datetime"], // 交易时间
            "returncode" => $_REQUEST["returncode"]
        );
        $Md5key = C('__PAYKEY__');

        ksort($ReturnArray);
        reset($ReturnArray);
        $md5str = "";
        foreach ($ReturnArray as $key => $val) {
            $md5str = $md5str . $key . "=>" . $val . "&";
        }
        $sign = strtoupper(md5($md5str . "key=" . $Md5key));
        if ($sign == $_REQUEST["sign"]) {
            if ($_REQUEST["returncode"] == "00") {
                $orderid = $ReturnArray['orderid'];
                $this->assign("title", "支付成功");
                $this->assign('msg', "交易成功！订单号：$orderid<br><font color=\"red\">3秒后自动返回</font>");
                $this->display("pay_info");
            }
        }
    }

    public function pay_server() {
        $ReturnArray = array( // 返回字段
            "memberid" => $_REQUEST["memberid"], // 商户ID
            "orderid" =>  $_REQUEST["orderid"], // 订单号
            "amount" =>  $_REQUEST["amount"], // 交易金额
            "datetime" =>  $_REQUEST["datetime"], // 交易时间
            "returncode" => $_REQUEST["returncode"]
        );
        $Md5key = C('CNZYZF')['__PAYKEY__'];

        /////////////////////////////////////////////////
        ksort($ReturnArray);
        reset($ReturnArray);
        $md5str = "";
        foreach ($ReturnArray as $key => $val) {
            $md5str = $md5str . $key . "=>" . $val . "&";
        }
        $sign = strtoupper(md5($md5str . "key=" . $Md5key));
        $fp = fopen('chongzhi_return.txt','w+');
        fwrite($fp,$_REQUEST["sign"]."---".$sign);
        fclose($fp);

        if ($sign == $_REQUEST["sign"]) {
            if ($_REQUEST["returncode"] == "00") {
                $pbank = $_REQUEST["reserved1"];

                $trade_source = 0;
                $remark = "微信充值";
                switch ($pbank) {
                    case "WXZF":
                        $trade_source = 2;
                        $remark = "微信充值";
                        break;
                    case "ZFB" :
                        $trade_source = 3;
                        $remark = "支付宝充值";
                        break;
                    case "SPDB" :
                        $trade_source = 4;
                        $remark = "银联充值";
                        break;
                }

                if(preg_match('/(\d+)?'.C('CNZYZF')['__PAYNO__'].'/i', $ReturnArray['orderid'], $matches)) {
                    // $userid = $matches[1];
                    $model = M("Pay");
                    /*$model->status = 1;
                    $model->where('order_id='.$ReturnArray['orderid'])->save(); // 根据条件更新*/

                    $payMap['order_id'] = $ReturnArray['orderid'];
                    $payMap['status'] = 1;
                    $payObj = $model->where($payMap)->find(); // 根据条件查找
                    if (!empty($payObj)) {
                        $user_id = $payObj['user_id'];
                        $money = floatval($payObj['amount']);
                        $out_trade_no = $payObj['order_id'];
                        $payObj['status'] = 2;
                        $model->save($payObj);
                        $this->updateUserMoney($money, $out_trade_no, $user_id, $remark, $trade_source);
                        $payObj['status'] = 3;
                        $model->save($payObj);

                        $fp = fopen('chongzhi_rel.txt','w+');
                        fwrite($fp, "OK");
                        fclose($fp);

                        exit('OK');

                    } else {
                        $fp = fopen('chongzhi_rel.txt','w+');
                        fwrite($fp,"错误3");
                        fclose($fp);
                    }
                } else {
                    $fp = fopen('chongzhi_rel.txt','w+');
                    fwrite($fp,"商户号对不上");
                    fclose($fp);
                }
            } else {
                $fp = fopen('chongzhi_rel.txt','w+');
                fwrite($fp,"错误2");
                fclose($fp);
            }
        } else {
            $fp = fopen('chongzhi_rel.txt','w+');
            fwrite($fp,"错误1");
            fclose($fp);
        }
        /*$result=file_get_contents('php://input', 'r');
        $tmp = explode("|", $result);
        $resp_xml = base64_decode($tmp[0]);
        $resp_sign = $tmp[1];
        if(PayUtils::test_verity(md5($resp_xml,true),$resp_sign)) { //验签
            $postObj = simplexml_load_string($resp_xml);

            $fp = fopen('test_log.txt','w+');
            fwrite($fp,$resp_xml);
            fclose($fp);

            $order_id = $postObj['merchantOrderId'];
            $model = M("Pay");
            $payMap['order_id'] = array('eq', $order_id."");
            $payMap['status'] = 1;
            $payObj = $model->where($payMap)->find(); // 根据条件查找

            if (!empty($payObj)) {
                $modelName = 'Sys';
                $model = M($modelName);
                $data = $model->field("recharge_fee")->where(array('id' => 1))->find();
                $rechargeMoney = floatval($payObj['amount']);
                $odds = $rechargeMoney * (floatval($data['recharge_fee'])/100);

                $money = $rechargeMoney-$odds;

                $user_id = $payObj['user_id'];
                $out_trade_no = $payObj['order_id'];

                $source = -1;
                $remark = "";
                if ($payObj['type'] == "WeiXinScanOrder") {
                    $source = 2;
                    $remark = "微信扫码";
                } else if ($payObj['type'] == "ZFBScanOrder") {
                    $source = 3;
                    $remark = "支付宝扫码";
                } else if ($payObj['type'] == "CertPayOrderH5") {
                    $source = 4;
                    $remark = "银联快充";
                }

                $model = M("TradeDetail");
                $tradeDetailMap["out_trade_no"] = $out_trade_no;
                $tradeDetailMap["type"] = 5;
                $tradeDetail_data = $model->where($tradeDetailMap)->count("id");


                if ($tradeDetail_data == 0) {
                    $model = M("User");
                    $data["id"] = $user_id;
                    $data['balance'] = array('exp','balance+'.$money);
                    $model->save($data);
                    $user_data = $model->field("balance")->where("id=$user_id")->find();

                    // Events::eventsHandle($user_id, $money);

                    // 添加充值记录
                    $rechargeWithdrawals = array("user_id"=>$user_id, "out_trade_no"=>$out_trade_no, "money"=>$rechargeMoney, "type"=>1,
                        "state"=>1, "remark"=>$remark, "datetime"=>date('Y-m-d H:i:s'));
                    RechargeWithdrawalsApi::add($rechargeWithdrawals);

                    // 添加资金流水
                    $tradeDetail = array("user_id"=>$user_id, "deal_user_id"=>0, "out_trade_no"=>"$out_trade_no", "type"=>5,
                        "money"=>$rechargeMoney, "fee_money"=>$odds, "other_money"=>0,"balance"=>$user_data['balance'],
                        "source"=>$source,"state"=>1, "datetime"=>date('Y-m-d H:i:s'));
                    TradeDetailApi::add($tradeDetail);
                }
            }
        } else {
            $fp = fopen('log.txt','w+');
            fwrite($fp,'验签失败');
            fclose($fp);
            echo '验签失败';
        }*/
    }

    public function zitoNotify() {
        $result = file_get_contents("php://input");
        $result = json_decode($result, true);

        if ($result['success'] == true) {
            $model = M("Pay");
            $payMap['order_id'] = array("eq", $result['orderidinf']);
            $payMap['status'] = 1;
            $payObj = $model->where($payMap)->find(); // 根据条件查找

            if (!empty($payObj)) {
                $query_result = \Lib\PayApi\Zito\PaymentClient::query($result['orderId']);
                $query_result = json_decode($query_result, true);
                if ($query_result['success'] == true && $query_result['code'] == "0x0000") {
                    $order = $query_result['orderList'][0];
                    if ($order['state'] == 1) {
                        $payObj['status'] = 2;
                        $model->save($payObj);

                        $zito = C('ZITO');
                        $bank = "";
                        $trade_source = -1;
                        foreach ($zito['tongdao'] as $key => $val) {
                            foreach ($val as $key2 => $val2) {
                                if ($val2 == $order['getewayid']) {
                                    $bank = $key;
                                    break;
                                }
                            }
                        }
                        $remark = "融智付";
                        if ($bank == "ALIPAY") {
                            $trade_source = 3;
                            $remark = "支付宝充值";
                        }

                        $user_id = $payObj['user_id'];
                        $money = floatval($payObj['amount']);
                        $out_trade_no = $payObj['order_id'];
                        if ($this->updateUserMoney($money, $out_trade_no, $user_id, $remark, $trade_source)) {
                            $payObj['status'] = 3;
                            $model->save($payObj);
                        }
                    }
                }
            } else {
                $fp = fopen('zito_chongzhi_rel.txt','w+');
                fwrite($fp, "没有找到订单：".$result['orderidinf']);
                fclose($fp);
            }
        }

        /*$result = \Lib\PayApi\Zito\PaymentClient::pay($orderNo, $money, $pbank);
        $result = json_decode($result, true);*/

        /*$fp = fopen('zito_chongzhi_rel.txt','w+');
        fwrite($fp, $result);
        fclose($fp);*/
    }
	
	public function baifupassNotify() {
        if ($_REQUEST["bftcode"] == "1000") {
            $order_no = $_REQUEST["orderNumber"];

            $model = M("Pay");
            $payMap['order_id'] = array("eq", $order_no);
            $payMap['status'] = 1;
            $payObj = $model->where($payMap)->find(); // 根据条件查找
            if (!empty($payObj)) {
                $payObj['status'] = 2;
                $model->save($payObj);

                $type = $payObj["type"];
                $remark = "百付通";
                $trade_source = -1;
                if (strstr($type,"WXZF")) {
                    $trade_source = 2;
                    $remark = "微信充值";
                } else if (strstr($type,"UNIONPAY")) {
                    $trade_source = 4;
                    $remark = "银联快捷";
                }

                $user_id = $payObj['user_id'];
                $money = floatval($payObj['amount']);
                $out_trade_no = $payObj['order_id'];
                if ($this->updateUserMoney($money, $out_trade_no, $user_id, $remark, $trade_source)) {
                    $payObj['status'] = 3;
                    $model->save($payObj);

                    exit("SUCCESS");
                } else {
                    $fp = fopen('baifupass_chongzhi_rel.txt','w+');
                    fwrite($fp, "充值失败：".$order_no);
                    fclose($fp);
                }

                // $sign = $_REQUEST["sign"];

                // $baifupass = C('BAIFUPASS');

                // $arr = \Lib\PayApi\Baifupass\PaymentClient::ArrDecode($sign);

                /*$type = $payObj["type"];
                $banks = explode('_',$type);

                $arr['appid'] = $baifupass['appid'];//appid//找管理员
                $arr['trxType'] = $baifupass['tongdao'][$banks[0]][$banks[1]];//支付形态 微信扫码  WX_SCANCODE  微信收银台  WX_SCANCODE_JSAPI 阿里扫码  Alipay_SCANCODE   阿里收银台 Alipay_SCANCODE_JSAPI
                $arr['amount'] = $money;//单位元 个位与十位不能相同不能为0 比如 10 11 都不行
                $arr['down_trade_no'] = $order_no;//订单号
                $arr['goodsname'] = "无";//备注
                $arr['backurl'] = $baifupass['notifyUrl'];//回调地址*/

            } else {
                $fp = fopen('baifupass_chongzhi_rel.txt','w+');
                fwrite($fp, "没有找到订单：".$order_no);
                fclose($fp);
            }

        } else {
            $fp = fopen('baifupass_chongzhi_rel.txt','w+');
            fwrite($fp, "没有找到订单：".$_REQUEST['bftcode']);
            fclose($fp);
        }
    }

    public function yekapayNotify() {
        $r0_Cmd = $_REQUEST['r0_Cmd'];
        $r1_Code = $_REQUEST['r1_Code'];
        $r2_TrxId = $_REQUEST['r2_TrxId'];
        $r3_Amt = $_REQUEST['r3_Amt'];
        $r4_Cur = $_REQUEST['r4_Cur'];
        $r5_Pid = $_REQUEST['r5_Pid'];
        $r6_Order = $_REQUEST['r6_Order'];
        $r7_Uid	= $_REQUEST['r7_Uid'];
        $r8_MP	= $_REQUEST['r8_MP'];
        $r9_BType = $_REQUEST['r9_BType'];
        $hmac = $_REQUEST['hmac'];

        $bRet = \Lib\PayApi\YeKaPay\PaymentClient::CheckHmac($r0_Cmd,$r1_Code,$r2_TrxId,$r3_Amt,$r4_Cur,$r5_Pid,$r6_Order,$r7_Uid,$r8_MP,$r9_BType,$hmac);

        if($bRet) {
            if($r1_Code=="1") {
                #	需要比较返回的金额与商家数据库中订单的金额是否相等，只有相等的情况下才认为是交易成功.
                #	并且需要对返回的处理进行事务控制，进行记录的排它性处理，在接收到支付结果通知后，判断是否进行过业务逻辑处理，不要重复进行业务逻辑处理，防止对同一条交易重复发货的情况发生.
                if($r9_BType=="1"){
                    echo "交易成功";
                    // echo  "<br />在线支付页面返回";
                } elseif($r9_BType=="2") {
                    #如果需要应答机制则必须回写流,以success开头,大小写不敏感.

                    $model = M("Pay");
                    $payMap['order_id'] = array("eq", $r6_Order);
                    $payMap['status'] = 1;
                    $payObj = $model->where($payMap)->find(); // 根据条件查找
                    if (!empty($payObj)) {
                        $payObj['status'] = 2;
                        $model->save($payObj);

                        $type = $payObj["type"];
                        $remark = "易云卡";
                        $trade_source = -1;
                        if (strstr($type,"WXZF")) {
                            $trade_source = 2;
                            $remark = "微信充值";
                        } else if (strstr($type,"UNIONPAY")) {
                            $trade_source = 4;
                            $remark = "银联快捷";
                        }

                        $user_id = $payObj['user_id'];
                        $money = floatval($payObj['amount']);
                        $out_trade_no = $payObj['order_id'];
                        if ($this->updateUserMoney($money, $out_trade_no, $user_id, $remark, $trade_source)) {
                            $payObj['status'] = 3;
                            $model->save($payObj);
                            exit("success");
                        } else {
                            $fp = fopen('yekapay_chongzhi_rel.txt','w+');
                            fwrite($fp, "充值失败：".$r6_Order);
                            fclose($fp);
                        }

                    } else {
                        $fp = fopen('yekapay_chongzhi_rel.txt','w+');
                        fwrite($fp, "没有找到订单：".$r6_Order);
                        fclose($fp);
                    }

                    echo "success";
                    /*echo "<br />交易成功";
                    echo  "<br />在线支付服务器返回";*/
                }
            }
        } else {
            echo "交易信息被篡改";
        }
    }

	public function rightyooNotify() {
		$result = file_get_contents("php://input");
        $result = json_decode($result, true);

        $model = M("Pay");
		$payMap['order_id'] = array("eq", $result['out_trade_no']);
		$payMap['status'] = 1;
		$payObj = $model->where($payMap)->find(); // 根据条件查找

		if (!empty($payObj)) {
			$payObj['status'] = 2;
			$model->save($payObj);

			$type = $payObj["type"];
			$remark = "蓝海支付";
			$trade_source = -1;
			if (strstr($type,"WXZF")) {
				$trade_source = 2;
				$remark = "微信充值";
			}

			$user_id = $payObj['user_id'];
			$money = floatval($payObj['amount']);
			$out_trade_no = $payObj['order_id'];
			if ($this->updateUserMoney($money, $out_trade_no, $user_id, $remark, $trade_source)) {
				$payObj['status'] = 3;
				$model->save($payObj);
				exit("SUCCESS");
			}
		} else {
			$fp = fopen('rightyoo_chongzhi_rel.txt','w+');
			fwrite($fp, "没有找到订单：".$result['orderidinf']);
			fclose($fp);
		}
	}
	
    private function updateUserMoney($money, $out_trade_no, $user_id, $remark, $trade_source) {
        $model = M("Pay");
        $payMap['order_id'] = array("eq", $out_trade_no);
        $payMap['status'] = 2;
        $pay_count = $model->where($payMap)->count(); // 根据条件查找
        if ($pay_count > 0) {
            $modelName = 'Sys';
            $model = M($modelName);
            $data = $model->field("recharge_fee")->where(array('id' => 1))->find();
            $rechargeMoney = floatval($money);
            $odds = $rechargeMoney * (floatval($data['recharge_fee'])/100);

            $money = $rechargeMoney-$odds;

            $model = M("TradeDetail");
            $tradeDetailMap["out_trade_no"] = $out_trade_no;
            $tradeDetailMap["type"] = 5;
            $tradeDetail_data = $model->where($tradeDetailMap)->count("id");

            if ($tradeDetail_data == 0) {
                $model = M("User");
                $data["id"] = $user_id;
                $data['balance'] = array('exp','balance+'.$money);
				$data['recharge'] = array('exp','recharge+'.$money);
                $model->save($data);
                $user_data = $model->field("balance")->where("id=$user_id")->find();

                // Events::eventsHandle($user_id, $money);

                 // 添加充值记录
                $rechargeWithdrawals = array("user_id"=>$user_id, "out_trade_no"=>$out_trade_no, "source"=>1, "money"=>$rechargeMoney, "type"=>1,
                    "state"=>1, "remark"=>$remark, "datetime"=>date('Y-m-d H:i:s'), "audit_date"=>date('Y-m-d H:i:s'), "audit_state"=>1);
                RechargeWithdrawalsApi::add($rechargeWithdrawals);

                // 添加资金流水
                $tradeDetail = array("user_id"=>$user_id, "deal_user_id"=>0, "out_trade_no"=>"$out_trade_no", "type"=>5,
                    "money"=>$rechargeMoney, "fee_money"=>$odds, "other_money"=>0,"balance"=>$user_data['balance'],
                    "source"=>$trade_source, "state"=>1, "datetime"=>date('Y-m-d H:i:s'));
                TradeDetailApi::add($tradeDetail);
                return true;
            }
        }
        return false;
    }

    public function pay_server_test() {
        $result=file_get_contents('php://input', 'r');
        $tmp = explode("|", $result);
        $resp_xml = base64_decode($tmp[0]);
        $resp_sign = $tmp[1];
        if(PayUtils::test_verity(md5($resp_xml,true),$resp_sign)) { //验签
            // echo '<br/>响应结果<br/><textarea cols="120" rows="20">'.$resp_xml.'</textarea>';
            $fp = fopen('withdrawals_log.txt', 'w+');
            fwrite($fp, $resp_xml);
            fclose($fp);
        }
    }

    public function cai1PayNotify() {
        $billno = $_POST['MerOrderNo'];
        $amount = $_POST['Amount'];
        $mydate = $_POST['OrderDate'];
        $succ = $_POST['Succ'];
        $msg = $_POST['Msg'];
        $attach = $_POST['GoodsInfo'];
        $ipsbillno = $_POST['SysOrderNo'];
        $retEncodeType = $_POST['RetencodeType'];
        $currency_type = $_POST['Currency'];
        $signature = $_POST['Signature'];

        // Md5摘要认证
        $content = $billno . $amount . $mydate . $succ . $ipsbillno . $currency_type;

        $cai1Pay = C('Cai1Pay');
        //请在该字段中放置商户登陆mer.easy8pay.com下载的证书
        $cert = $cai1Pay['Mer_key'];
        $signature_1ocal = md5($content . $cert);

        if ($signature_1ocal == $signature) {
            //  判断交易是否成功
            if ($succ == 'Y') {
                $order_no = $billno;

                $model = M("Pay");
                $payMap['order_id'] = array("eq", $order_no);
                $payMap['status'] = 1;
                $payObj = $model->where($payMap)->find(); // 根据条件查找
                if (!empty($payObj)) {
                    $payObj['status'] = 2;
                    $model->save($payObj);

                    $remark = "财易付-支付宝充值";
                    $trade_source = 3;

                    $user_id = $payObj['user_id'];
                    $money = floatval($payObj['amount']);
                    $out_trade_no = $payObj['order_id'];
                    if ($this->updateUserMoney($money, $out_trade_no, $user_id, $remark, $trade_source)) {
                        $payObj['status'] = 3;
                        $model->save($payObj);
                        //交易成功返回“success”标识
                        //echo 'success';
                        exit("success");
                    } else {
                        $fp = fopen('cai1pay_chongzhi_rel.txt', 'w+');
                        fwrite($fp, "充值失败：" . $order_no);
                        fclose($fp);
                    }
                }

            }
            else {
                //没有找到订单
                $fp = fopen('cai1pay_chongzhi_rel.txt','w+');
                fwrite($fp, "没有找到订单：".$billno);
                fclose($fp);
            }
        }
        else {
            //签名不正确
            $fp = fopen('cai1pay_chongzhi_rel.txt','w+');
            fwrite($fp, "订单签名不正确：".$billno);
            fclose($fp);
        }
    }
}